<template>
  <div class="luggage-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title-bold">行李转盘管理</span>
          <div class="search-bar">
            <el-input
              v-model="searchQuery.flid"
              placeholder="航班号"
              style="width: 150px; margin-right: 10px"
              clearable
            />
            <el-button type="primary" @click="fetchBaggageBelts">
              查询
            </el-button>
            <el-button @click="resetSearch">
              重置
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="baggageBelts"
        border
        style="width: 100%"
        v-loading="loading"
        highlight-current-row
      >
        <el-table-column prop="DFLT_FLID" label="航班号" min-width="120" />
        <el-table-column prop="BTNO" label="行李转盘编号" min-width="120" />
        <el-table-column prop="CODE" label="行李转盘代码" min-width="120" />
        <el-table-column prop="ESTR" label="预计开始时间" min-width="180">
          <template #default="{ row }">
            {{ formatDisplayTime(row.ESTR) }}
          </template>
        </el-table-column>

        <el-table-column prop="EEND" label="预计结束时间" min-width="180">
          <template #default="{ row }">
            {{ formatDisplayTime(row.EEND) }}
          </template>
        </el-table-column>

        <el-table-column prop="RSTR" label="实际开始时间" min-width="180">
          <template #default="{ row }">
            {{ formatDisplayTime(row.RSTR) }}
          </template>
        </el-table-column>

        <el-table-column prop="REND" label="实际结束时间" min-width="180">
          <template #default="{ row }">
            {{ formatDisplayTime(row.REND) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="100" fixed="right">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row)">
              {{ getStatus(row) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 修改为详情按钮 -->
        <el-table-column label="操作" width="120" align="center" fixed="right" v-if="$store.getters.currentRole === 'admin'">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              plain
              @click="showDetailDialog(row)"
              class="deep-blue-btn"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="行李转盘详情" width="40%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="航班号">{{ detailForm.dfltFlid || '-' }}</el-descriptions-item>
        <el-descriptions-item label="行李转盘编号">{{ detailForm.btno || '-' }}</el-descriptions-item>
        <el-descriptions-item label="行李转盘代码">{{ detailForm.code || '-' }}</el-descriptions-item>
        <el-descriptions-item label="预计开始时间">{{ formatDisplayTime(detailForm.estr) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="预计结束时间">{{ formatDisplayTime(detailForm.eend) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="实际开始时间">{{ formatDisplayTime(detailForm.rstr) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="实际结束时间">{{ formatDisplayTime(detailForm.rend) || '-' }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { FlightApi } from '@/api/flight'
import { ElMessage } from 'element-plus'

// 响应式变量
const baggageBelts = ref([])
const loading = ref(false)
const searchQuery = ref({
  flid: '',
  btno: ''
})
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const detailDialogVisible = ref(false)
const detailForm = ref({
  dfltFlid: '',
  btno: '',
  code: '',
  estr: '',
  eend: '',
  rstr: '',
  rend: ''
})

// 状态判断方法
const getStatus = (row) => {
  if (row.RSTR && row.REND) return '已完成'
  else if (row.RSTR && !row.REND) return '运行中'
  else if (row.ESTR && row.EEND) return '待开始'
  else return '未分配'
}

const getStatusTag = (row) => {
  const status = getStatus(row)
  const map = {
    已完成: 'success',
    运行中: 'primary',
    待开始: 'warning',
    未分配: 'info'
  }
  return map[status] || ''
}

// 获取行李转盘数据
const fetchBaggageBelts = async () => {
  try {
    loading.value = true
    let res

    if (searchQuery.value.flid) {
      res = await FlightApi.getBaggageBeltsByFlightId(
        searchQuery.value.flid,
        pagination.value.currentPage,
        pagination.value.pageSize
      )
    } else {
      res = await FlightApi.getBaggageBelts(
        pagination.value.currentPage,
        pagination.value.pageSize
      )
    }

    baggageBelts.value = res.data || []
    pagination.value.total = res.totalRecords || 0

    // 如果查询特定转盘编号
    if (searchQuery.value.btno) {
      baggageBelts.value = baggageBelts.value.filter(item =>
        item.BTNO.includes(searchQuery.value.btno)
      )
      pagination.value.total = baggageBelts.value.length
    }
  } catch (error) {
    console.error('获取行李转盘数据失败:', error)
    baggageBelts.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 新增格式化显示时间的方法
const formatDisplayTime = (timeStr) => {
  if (!timeStr) return '-'

  // 假设原始格式是YYYYMMDDHHmmss
  if (timeStr.length === 14) {
    const year = timeStr.substring(0, 4)
    const month = timeStr.substring(4, 6)
    const day = timeStr.substring(6, 8)
    const hour = timeStr.substring(8, 10)
    const minute = timeStr.substring(10, 12)
    return `${year}-${month}-${day} ${hour}:${minute}`
  }

  // 如果是其他格式，尝试解析为Date对象
  try {
    const date = new Date(timeStr)
    if (isNaN(date.getTime())) return timeStr // 如果解析失败，返回原始值

    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
  } catch {
    return timeStr
  }
}

// 显示详情对话框
const showDetailDialog = (row) => {
  if (!row.DFLT_FLID) {
    ElMessage.warning('该记录无 DFLT_FLID，无法查看详情')
    return
  }

  detailForm.value = {
    dfltFlid: row.DFLT_FLID,
    btno: row.BTNO,
    code: row.CODE,
    estr: row.ESTR,
    eend: row.EEND,
    rstr: row.RSTR,
    rend: row.REND
  }
  detailDialogVisible.value = true
}

onMounted(() => {
  fetchBaggageBelts()
})

// 搜索和分页处理
const resetSearch = () => {
  searchQuery.value = {
    flid: '',
    btno: ''
  }
  pagination.value.currentPage = 1
  fetchBaggageBelts()
}

const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  fetchBaggageBelts()
}

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchBaggageBelts()
}
</script>

<style scoped>
.title-bold {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}
.luggage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer button:not(:last-child) {
  margin-right: 10px;
}

.deep-blue-btn {
  --el-button-primary-border-color: #1a73e8; /* 更深的蓝色边框 */
  --el-button-primary-text-color: #1a73e8; /* 更深的蓝色文字 */
}
</style>
